package com.feng.online_xdclass.interceptor;

import com.feng.online_xdclass.exception.XDexception;
import com.feng.online_xdclass.model.entity.User;
import com.feng.online_xdclass.utils.JWTUtils;
import com.feng.online_xdclass.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 进入到controller之前的方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getParameter("token");
        }
        if (StringUtils.isNoneBlank(token)) {
            Claims claims = JWTUtils.checkJWT(token);
            if (claims == null) {
                //告诉登录失败，登录过期，请重新登录
                throw new XDexception(-5,"用户登录过期,请重新登录");

            }
            Integer id = (Integer) claims.get("id");
            String name = (String) claims.get("name");

            User user = new User();
            user.setId(id);
            user.setName(name);

            UserThreadLocal.put(user);
            return true;
        }
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //用完得删除，如果不删除的话会有信息泄露的风险
        UserThreadLocal.remove();
    }
}
